package org.dna.metronomo.persistence.impl;

import java.util.List;
import org.apache.ibatis.session.SqlSession;
import org.apache.log4j.Logger;
import org.dna.metronomo.persistence.IModuleDAO;
import org.dna.metronomo.persistence.PersistenceException;
import org.dna.metronomo.persistence.impl.annotations.SessionField;
import org.dna.metronomo.persistence.impl.annotations.SessionMethod;
import org.dna.mybatis.criteria.Criteria;
import org.dna.mybatis.criteria.Restrictions;
import org.tigris.scarab.mapper.ModuleMapper;
import org.tigris.scarab.model.Module;

/**
 *
 * @author andrea
 */
public class IBatisModuleDAO implements IModuleDAO {
    
    @SessionField
    SqlSession m_session;

    private final static Logger LOG = Logger.getLogger(IBatisModuleDAO.class);

    @SessionMethod
    public void insert(final Module module) throws PersistenceException {
        //Check params
        if (module.getName() == null) {
            throw new IllegalArgumentException("Module.name must be valued");
        }
        if (module.getCode() == null) {
            throw new IllegalArgumentException("Module.code must be valued");
        }
        if (module.getDescription() == null) {
            throw new IllegalArgumentException("Module.description must be valued");
        }
        ModuleMapper mapper = m_session.getMapper(ModuleMapper.class);
        mapper.insert(module);

        LOG.info("Executing ModuleMapper.insert, inserted with " + module);
    }

    @SessionMethod
    public Module findByID(int key) throws PersistenceException {
        ModuleMapper mapper = m_session.getMapper(ModuleMapper.class);
            return mapper.selectByID(key);
    }

    @SessionMethod
    public Module findByName(String name) throws PersistenceException {
        final Criteria criteria = Criteria.create(Module.class).
        add(Restrictions.like("name", name));

        if (!criteria.verify()) {
            return null;
        }
        criteria.bind(m_session.getConfiguration());
        ModuleMapper mapper = m_session.getMapper(ModuleMapper.class);
        List<Module> modules =  mapper.selectByExample(criteria);
        if (modules.isEmpty()) {
            return null;
        }
        return modules.get(0);
    }
}
